#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理器 - 管理系统配置
"""

import json
import os
from pathlib import Path
from typing import Dict, Any


class ConfigManager:
    """配置管理器"""
    
    DEFAULT_CONFIG = {
        "parsing": {
            "confidence_threshold": 0.7,
            "min_table_rows": 2,
            "min_table_cols": 2,
            "image_min_size": 50,
            "text_min_length": 5
        },
        "classification": {
            "title_keywords": ["目标", "规划", "发展", "建设", "管理", "服务"],
            "narrative_min_length": 20,
            "list_indicators": ["•", "○", "▪", "1.", "2.", "3.", "(1)", "(2)", "(3)"]
        },
        "storage": {
            "storage_root": "storage",
            "create_backups": True,
            "compress_images": True,
            "max_file_size_mb": 100
        },
        "output": {
            "log_level": "INFO",
            "save_raw_data": True,
            "generate_summary": True,
            "export_formats": ["json"]
        }
    }
    
    @classmethod
    def load_config(cls, config_path: str = None) -> Dict[str, Any]:
        """加载配置文件"""
        if config_path and os.path.exists(config_path):
            with open(config_path, 'r', encoding='utf-8') as f:
                user_config = json.load(f)
            
            # 合并用户配置和默认配置
            config = cls._merge_configs(cls.DEFAULT_CONFIG, user_config)
        else:
            config = cls.DEFAULT_CONFIG.copy()
        
        return config
    
    @classmethod
    def save_config(cls, config: Dict[str, Any], config_path: str):
        """保存配置文件"""
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
    
    @classmethod
    def create_default_config(cls, config_path: str = "config/default.json"):
        """创建默认配置文件"""
        cls.save_config(cls.DEFAULT_CONFIG, config_path)
        print(f"默认配置文件已创建: {config_path}")
    
    @classmethod
    def _merge_configs(cls, default: Dict[str, Any], user: Dict[str, Any]) -> Dict[str, Any]:
        """递归合并配置"""
        result = default.copy()
        
        for key, value in user.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = cls._merge_configs(result[key], value)
            else:
                result[key] = value
        
        return result
    
    @classmethod
    def validate_config(cls, config: Dict[str, Any]) -> bool:
        """验证配置的有效性"""
        required_sections = ["parsing", "classification", "storage", "output"]
        
        for section in required_sections:
            if section not in config:
                print(f"配置错误: 缺少必需的配置节 '{section}'")
                return False
        
        # 验证数值范围
        parsing = config.get("parsing", {})
        if "confidence_threshold" in parsing:
            threshold = parsing["confidence_threshold"]
            if not (0.0 <= threshold <= 1.0):
                print(f"配置错误: confidence_threshold 必须在 0.0-1.0 之间，当前值: {threshold}")
                return False
        
        return True


if __name__ == "__main__":
    # 创建默认配置文件
    ConfigManager.create_default_config()